I’ve been playing with building out a Connect pod (blog entry & webinar coming soon ™) but in the meantime thought I’d share a little code for writing to and reading from a DynamoDB.
(Just as a reminder, you can find info about getting a DynamoDB object up and running here: https://helpx.adobe.com/coldfusion/using/integrate-coldfusion-dynamodb.html)
So first a few assumptions. I will assume you have created a DynamoDB object connected to DynamoDB in AWS with a table named “DemoTable”. I will further assume that your AWS connector is named “aws” and your dynamo object is named DynamoConnector.
So let’s begin by instantiating the object, and naming it “dynamoObject”.
dynamoObject = getCloudService("aws", "ConnectScheduler");
We will be using “dynamoObject” to both read from and write to the DB.
Now that we have an object to target, let’s build the query that returns the data from the db.
tableName = "DemoTable"; scanStruct = { "TableName": "#tableName#" } scanresponse = dynamoObject.scan(scanStruct);
OK so what did we do? First we set a variable to the name of the table, “DemoTable”, then we create a struct that sets the value “TableName” to that value, which is then passed into Dynamo using the scan() function. So now the variable “scanresponse” will hold the data returned from the db.
Now, something to consider here is that the return from DynamoDB is very “noisy”. The full return includes things like http codes and other things which we may or may not care about, as well as an array which includes structures which themselves include the data we want.
If we assume that the data which returns from DynamoDB includes first_name, last_name, and favorite_cake, you would return it in the following fashion:
for (item in scanresponse.items){ // Output values from DB writeOutput( "<b>First Name: </b>" &item.first_name.S &" | " &"<b>Last Name: </b>" &item.last_name.S &" | " & "<b>Favorite Cake: </b>" & item.favorite_cake.S & "<br>") ; }
<form name="aform" method="post" action="dynamo-example.cfm"> First Name: <input type="text" name="first_name" id="first_name" value="" /><br /> Last Name: <input type="text" name="last_name" id="last_name" value="" /><br /> Favorite Cake: <input type="text" name="favorite_cake" id="favorite_cake" value="" /><br /> <input type="submit" name="submit" value="submit" /> </form>
if(isDefined("FORM.submit")){ putItemStruct = { "TableName":"#TableName#", "Item":{ "SampleKey": "#createUUID()#", "first_name": FORM.first_name, "last_name": FORM.last_name, "favorite_cake": FORM.favorite_cake }, "ReturnValues":"NONE" } try { putItemResponse=dynamoObject.putItem(putItemStruct,{"hasType": false}) writeOutput("Item inserted successfully in the table.") writeDump(putItemResponse) } catch (any e){ writeDump(e) } } }
You must be logged in to post a comment.